<template>
  <div class="container">
    <div class="header">
      <h2>{{ headerTitle }}</h2>
      <!-- <el-button type="success" @click="showSearchDialog = true"
        >查找</el-button
      > -->
    </div>

    <!-- 展示表格 -->
    <div class="table-container">
      <div class="table-wrapper">
        <!-- TODO: 分页位置并不固定，70vh的时候贴近底部，60vh的时候贴近表格 -->
        <el-table :data="list" border stripe style="width: 100%; height: 60vh">
          <el-table-column
            v-for="(label, prop) in formPropMap"
            :key="prop"
            :prop="prop"
            :label="label"
            align="center"
          />
          <!-- 课程类型设置标签样式 -->
          <el-table-column prop="courseType" label="课程类型" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.courseType === '公共必修'"
                type="primary"
                >{{ scope.row.courseType }}</el-tag
              >
              <el-tag
                v-else-if="scope.row.courseType === '公共选修'"
                type="success"
                >{{ scope.row.courseType }}</el-tag
              >
              <el-tag
                v-else-if="scope.row.courseType === '专业必修'"
                type="warning"
                >{{ scope.row.courseType }}</el-tag
              >
              <el-tag
                v-else-if="scope.row.courseType === '专业选修'"
                type="info"
                >{{ scope.row.courseType }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                :disabled="scope.row.disabled"
                @click="handleSelect(scope.row.courseId)"
                >选课</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="params.page"
            v-model:page-size="params.size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { courseApi, enrollmentApi } from "@/api";
import { getUserId } from "@/auth";
import type { Course } from "@/types/api-types";
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";

type IdType = string;

// 页面标题
const headerTitle = ref("选课系统");

const defaultIdValue = "";
const defaultEditIdValue = defaultIdValue;
const defaultDeleteIdValue = defaultIdValue;

/**
 * 属性名称映射表
 */
const formPropMap = {
  courseId: "课程号",
  courseName: "课程名",
  credit: "学分",
  hours: "学时"
  // courseType: "课程类型",  // 将课程类型单独设置样式
  // description: "描述"
};

type CourseSelectionForm = {
  courseId: string;
  courseName: string;
  credit: string;
  hours: string;
  courseType: string;
  disabled?: boolean;  // 决定是否禁用选课按钮
};

// 更新、添加、查找三用表单
const updateForm = reactive<CourseSelectionForm>({
  courseId: "",
  courseName: "",
  credit: "",
  hours: "",
  courseType: ""
});

const showAddDialog = ref(false);
const showSearchDialog = ref(false);

// 分页相关
interface PageParams {
  page: number;
  size: number;
}

// 表格
const list = ref<CourseSelectionForm[]>([]);
// 数据总数
const total = ref(0);
// 分页请求参数
const params = ref<PageParams>({
  page: 1,
  size: 10
});

// 更新选课id
const editId = ref<IdType>(defaultEditIdValue);
// 编辑模式状态
const isEditMode = ref(false);

/**
 * 处理更新
 * @param id 选课id
 */
const handleSelect = async (id: IdType) => {
  try {
    await enrollmentApi.selectCourse(getUserId() as string, id);
    ElMessage.success("选课成功");
  } catch (error) {
    ElMessage.error("选课失败");
    console.error("选课失败：", error);
  } finally {
    id = defaultIdValue;
  }
};

const handleSearch = async () => {
  try {
  } catch (error) {
    ElMessage.error("查找失败");
    console.error("查找失败：", error);
  } finally {
  }
};

/**
 * 处理每页大小变化
 * @param val 每页大小
 */
const handleSizeChange = (val: number) => {
  params.value.size = val;
  params.value.page = 1;
  getList();
};

/**
 * 处理页面切换
 * @param val 页号
 */
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  getList();
};

const selectedCourses = ref();

// 过滤掉已选课程，退课在选课结果里面实现
const filterList = (list: Course[]) => {
  const selectedIds: Set<string> = new Set();
  for (let s of selectedCourses.value) {
    if (s.courseId) {
      selectedIds.add(s.courseId);
    }
  }

  return list.map((course) => ({
    ...course,
    disabled: selectedIds.has(course.courseId)
  }));
};

/**
 * 获取表格
 */
const getList = async () => {
  try {
    
    const { data } = await courseApi.getSelectedCoursesByStudentId(
      getUserId() as string
    );
    
    selectedCourses.value = data;
    
    // 获取课程
    const res = await courseApi.getPage({
      page: params.value.page - 1,
      size: params.value.size
    });
    console.log("获取的课程信息：", res.data);

    list.value = filterList(res.data.content);
    
    total.value = res.data.totalElements || 0;
  } catch (error) {
    ElMessage.error("表格获取失败");
    console.error("表格获取失败：", error);
  }
};

onMounted(async () => {
  await getList();
});
</script>

<style lang="css">
.container {
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;

  h2 {
    margin: 0;
    color: #303133;
  }
}

.table-container {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
}

.pagination {
  flex-shrink: 0;
  background: white;
  padding: 10px 0;
}

.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
